<template>
  <a-layout>
    <a-layout-content
        :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }"
    >
      <p>
        <a-space type="small">
          <a-input-search
              v-model:value="searchName"
              placeholder="请输入名称(只支持一级分类)"
              enter-button="搜索"
              size="large"
              style="width: 400px"
              allow-clear
              @search="handleSearch"
          />
          <a-button type="primary" @click="add()" size="large">
            新增
          </a-button>
        </a-space>
      </p>
      <a-table :columns="columns"
               :row-key="record => record.id"
               :data-source="categoryTree"
               :pagination="false"
               :loading="loading"
      >
        <template #cover="{ text:cover }">
          <img v-if="cover" :src="cover" alt="avatar"/>
        </template>
        <template v-slot:action="{text,record}">
          <a-space type="small">
            <a-button type="primary" @click="edite(record)">
              编辑
            </a-button>
            <a-button type="danger" @click="deleteById(record.id)">
              删除
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-layout-content>
  </a-layout>

  <a-modal
      title="分类表单"
      v-model:visible="modalVisible"
      :confirm-loading="modalLoading"
      @ok="modalHandleOk"
  >
    <a-form :model="category" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="名称">
        <a-input v-model:value="category.name"/>
      </a-form-item>
      <a-form-item label="顺序">
        <a-input v-model:value="category.sort"/>
      </a-form-item>
      <a-form-item label="父分类">
        <a-select
            v-model:value="category.parent"
            ref="select"
        >
          <a-select-option value="0">
            无
          </a-select-option>
          <a-select-option v-for="item in categoryTree"
                           :key="item.id"
                           :value="item.id"
                           :disabled="category.id===item.id">
            {{item.name}}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>

</template>

<script lang="ts">
import {createVNode, defineComponent, onMounted, ref} from 'vue';
import axios from 'axios';
import {Tool} from "@/utils/tool";
import {Modal} from "ant-design-vue";
import {ExclamationCircleOutlined} from "@ant-design/icons-vue";



export default defineComponent({
  name: 'AdminCategory',
  setup() {

    const categorys = ref();

    // 表格树形结构
    const categoryTree = ref();

    const loading = ref(false);

    const columns = [
      {
        title: '名称',
        dataIndex: 'name'
      },
      {
        title: '排序',
        key: 'sort',
        dataIndex: 'sort'
      },
      {
        title: '父分类',
        key: 'parent',
        dataIndex: 'parent'
      },
      {
        title: '操作',
        key: 'action',
        slots: {customRender: 'action'}
      }
    ];

    // 模态框
    const modalVisible = ref<boolean>(false);
    const modalLoading = ref<boolean>(false);

    // 表单
    const category = ref();

    // 搜索
    const searchName = ref();

    /**
     * 修改
     * @param record
     */
    const edite = (record: any) => {
      modalVisible.value = true;
      category.value = record;
    };

    /**
     * 删除
     * @param record
     */
    const deleteById = (record: any) => {
      Modal.confirm({
        title: () => '你确定要选择删除以下文档吗？',
        icon: () => createVNode(ExclamationCircleOutlined),
        content: () => '被删除后文档将无法恢复',
        onOk() {
          axios.delete("/category/delete", {
            params: {
              id: record
            }
          }).then((response) => {
            const data = response.data;
            if (data.success) {
              handleQuery({
                name: searchName.value
              });
            }
          });
        },
        // eslint-disable-next-line @typescript-eslint/no-empty-function
        onCancel() {},
      });
    };

    /**
     * 新增
     * @param record
     */
    const add = () => {
      modalVisible.value = true;
      category.value = {};
    };

    const modalHandleOk = () => {
      modalLoading.value = true;

      axios.post("/category/save", category.value).then((response) => {
        const data = response.data;

        if (data.success) {
          modalVisible.value = false;
          modalLoading.value = false;

          handleQuery({
            name: searchName.value
          });
        }

      });

    }

    /**
     * 搜索框查询
     */
    const handleSearch = () => {
      handleQuery({
        name: searchName.value
      });
    }

    /**
     * 数据查询
     **/
    const handleQuery = (params: any) => {
      loading.value = true;
      // 如果不清空现有数据，则编辑保存重新加载数据后，再点编辑，则列表显示的还是编辑前的数据
      categorys.value = [];
      axios.get("/category/all", {
        params: params
      }).then((response) => {
        loading.value = false;
        const data = response.data;
        categorys.value = data.content;
        categoryTree.value = [];

        categoryTree.value = Tool.array2Tree(categorys.value, 0);
      });
    };


    onMounted(() => {
      handleQuery({

      });
    });


    return {
      // categorys,
      categoryTree,
      columns,
      loading,
      //模态框
      modalVisible,
      modalLoading,
      edite,
      deleteById,
      modalHandleOk,
      //表单
      category,
      add,
      // 搜索
      handleSearch,
      searchName,
    }
  }
});
</script>

<style scoped>
img {
  width: 50px;
  height: 50px;
}
</style>
